<?php
/**
 * jishupu-cms
 * @Author:技术铺<jishupu@qq.com>
 * @Date:2021/11/11
 */

namespace App\Traits;

use Carbon\Carbon;
use DateTimeInterface;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

/**
 * 模型基础 Traits
 *
 * Trait BaseModel
 * @package App\Traits
 */
trait BaseModel
{
    // 软删除
    use SoftDeletes;

    /**
     * 为 array / JSON 序列化准备日期格式
     *
     * @param DateTimeInterface $date
     * @return string
     */
    /*    protected function serializeDate(DateTimeInterface $date) : string
        {
            return $date->format('Y-m-d H:i:s');
        }*/

    /**
     * batchUpdate 批量更新
     * @param array $multipleData 要求二维数组 [['id' => 1,'title' => '标题1'], ['id'=>2,'title' => '标题1']]
     * @param string $whereField 条件字段默认id
     * @param string $andCommonWhere 追加通用条件，格式：' did = ? and cid = ? ' 使用?占位
     * @param array $andCommonWhereData 追加通用条件的绑定值，与追加条件$andCommonWhere的?占位一一对应，如：[1,2]
     * @return false|int
     */
    public  function  batchUpdate($multipleData = [], $whereField = 'id', $andCommonWhere = "", $andCommonWhereData = [])
    {
        if (empty($multipleData) || count($multipleData) == count($multipleData, 1)) {
            return false;
        }
        try {
            $whereField = $whereField ?: 'id';
            $updateSql = " UPDATE " . DB::getTablePrefix() . $this->table . " SET  ";
            $updateColumn = array_keys(current($multipleData));
            $bindings = [];
            $set = "";
            foreach ($updateColumn as $column) {
                if ($whereField == $column) continue;
                $case = " `$column` = CASE `" . $whereField . "` ";
                foreach ($multipleData as $data) {
                    $case .= " WHEN ? THEN ? ";
                    $bindings[] = $data[$whereField];
                    $bindings[] = $data[$column];
                }
                $case .= " END , ";
                $set .= $case;
            }
            $whereFieldsArr = collect($multipleData)->pluck($whereField)->values()->all();
            $whereIn = str_repeat('?,', count($whereFieldsArr));
            $updateSql = $updateSql . $set . " updated_at = '" . Carbon::now() . "'" . " WHERE  `" . $whereField . "` in (" . rtrim($whereIn, ',') . ") ";
            $bindings = array_merge($bindings, $whereFieldsArr);
            if (!empty($andCommonWhere) && count($andCommonWhereData) > 0) {
                $updateSql .= " and " . $andCommonWhere;
                $bindings = array_merge($bindings, $andCommonWhereData);
            }
            return DB::update($updateSql, $bindings);
        } catch (\Exception $e) {
            return false;
        }
    }

}
